﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using EbbinghausWord.BLL;
using EbbinghausWord.Common;
using EbbinghausWord.Entities;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Media;

namespace EbbinghausWord.Pages
{
    public partial class ReviewWordPage : PhoneApplicationPage
    {
        public ReviewWordPage()
        {
            InitializeComponent();

            WordBookManager.IsNeedReflesh = true;

            //var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(33) };
            //timer.Tick += delegate { try { FrameworkDispatcher.Update(); } catch { } };
            //timer.Start();
        }

        #region private field
        private WordEntity _currentWord = null;
        private bool _isPlayVoice = false;
        #endregion

        #region override

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            var et = new ExecuteTimer(false);

            if (WordBookManager.IsNeedReflesh)
            {
                //清空队列
                WordQueueManager.InitQueue();
                et.Show("InitQueue");

                //显示第一个单词
                ShowFirstWord();
                et.Show("ShowFirstWord");
                WordBookManager.IsNeedReflesh = false;

                HideIsRightPanel();
                ShowIsKnowPanel();
            }


            base.OnNavigatedTo(e);
            while (NavigationService.CanGoBack)
            {
                var entry = NavigationService.RemoveBackEntry();
                //Debug.WriteLine(entry.Source);
            }
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel =
                MessageBoxResult.OK != MessageBox.Show("确认退出极速背单词吗？", "退出确认", MessageBoxButton.OKCancel);

            base.OnBackKeyPress(e);
        }

        #endregion

        #region callback

        private void AboutClick(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(@"/Pages/About.xaml", UriKind.Relative));
        }

        private void OptionClick(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(@"/Pages/Option.xaml", UriKind.Relative));
        }

        private void CompleteRemeberButton_Click(object sender, EventArgs e)
        {
            if (_currentWord == null)
            {
                Tools.ShowMessage("目前没有需要记忆的单词");
                return;
            }

            if (MessageBox.Show("当前单词加为熟词后，将不再出现在你的复习和学习计划中，是否继续？", "加为熟词",
                MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                HideIsRightPanel();
                HideNextPanel();

                _currentWord = WordBookManager.CompleteRemeberWord();
                ShowWord();
            }
        }

        private void studyAchievementBarIconButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/StudyAchievementPage.xaml", UriKind.Relative));
        }

        private void scoreBarIconButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/ScorePage.xaml", UriKind.Relative));
        }

        private void MainME_MediaOpened(object sender, RoutedEventArgs e)
        {
            MainME.Play();
        }

        private void MainME_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            //删除文件
            VoiceManager.DeleteVoiceFile(_currentWord.English);
            ShowVoiceImage();
            //重新下载
            Tools.ShowMessage("播放失败，发音文件被删除");
            MainME.Source = null;

            _isPlayVoice = false;
        }

        private void MainME_MediaEnded(object sender, RoutedEventArgs e)
        {
            MainME.Source = null;
            _isPlayVoice = false;
        }

        private void voiceButton_Click(object sender, RoutedEventArgs e)
        {
            PlayVoice();
        }

        private void selectBookButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(@"/Pages/SelectBookPage.xaml", UriKind.Relative));
        }

        private void noButton_Click(object sender, RoutedEventArgs e)
        {
            HideIsKnowPanel();
            ShowNextPanel();
        }

        private void yesButton_Click(object sender, RoutedEventArgs e)
        {
            HideIsKnowPanel();
            ShowIsRightPanel();
        }

        private void nextButton_Click(object sender, RoutedEventArgs e)
        {
            HideNextPanel();

            _currentWord = WordBookManager.ForgetWord();
            ShowWord();
        }

        private void noRightButton_Click(object sender, RoutedEventArgs e)
        {
            HideIsRightPanel();

            _currentWord = WordBookManager.ForgetWord();
            ShowWord();
        }

        private void rightButton_Click(object sender, RoutedEventArgs e)
        {
            var et = new ExecuteTimer(false);

            HideIsRightPanel();
            et.Show("HideIsRightPanel");
            if (_currentWord != null)
            {
                _currentWord = WordBookManager.RememberWord();
            }
            et.Show("RememberWord");

            ShowWord();
            et.Show("ShowWord");
        }

        private void voiceClick(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(@"/Pages/VoicePage.xaml", UriKind.Relative));
        }

        private void feedbackClick(object sender, EventArgs e)
        {
            FeedbackManager.OpenFeedbackMail();
        }

        private void rankClick(object sender, EventArgs e)
        {
            FeedbackManager.OpenRank();
        }

        #endregion

        #region private method

        /// <summary>
        /// 播放声音
        /// </summary>
        private void PlayVoice()
        {
            if (_isPlayVoice) return;
            _isPlayVoice = true;

            var voiceManager = new VoiceManager();

            //下载进度条
            SystemTray.ProgressIndicator = new ProgressIndicator
            {
                IsVisible = false,
                IsIndeterminate = true,
                Text = "下载单词发音文件..."
            };
            voiceManager.VoiceDownloading += (s, ex) => SetProgressIndicator(true);

            voiceManager.GetVoiceCompleted += (s, ex) =>
            {
                //关闭后台播放的音乐
                if (MediaPlayer.Queue.Count > 0)
                {
                    FrameworkDispatcher.Update();
                    MediaPlayer.Pause();
                    FrameworkDispatcher.Update();
                }
                //播放发音
                MainME.SetSource(ex.VoiceFileStream);
                MainME.Position = new TimeSpan(0);
                ShowVoiceImage();
                SetProgressIndicator(false);
            };

            voiceManager.GetVoiceFailed += (s, ex) =>
            {
                Tools.ShowMessage("单词发音文件获取失败，请检查网络连接");
                ShowVoiceImage();
                _isPlayVoice = false;
                SetProgressIndicator(false);
                //SystemTray.ProgressIndicator.IsVisible = false;
            };

            voiceManager.GetVoiceAsync(_currentWord.English);
        }

        /// <summary>
        /// 设置进度条是否显示
        /// </summary>
        /// <param name="isShow"></param>
        private void SetProgressIndicator(bool isShow)
        {
            if (SystemTray.ProgressIndicator != null)
            {
                SystemTray.ProgressIndicator.IsVisible = isShow;
            }
        }

        /// <summary>
        /// 隐藏中文及音标面板
        /// </summary>
        private void HideChinesePanel()
        {
            chinesePanel.Visibility = Visibility.Collapsed;
            isKownTextPanel.Visibility = Visibility.Visible;
            //ShowChineseButton.Visibility = Visibility.Visible;
            //ForgetWordButton.IsEnabled = false;
            //RemeberWordButton.IsEnabled = false;
        }

        /// <summary>
        /// 显示中文及音标面板
        /// </summary>
        private void ShowChinesePanel()
        {
            chinesePanel.Visibility = Visibility.Visible;
            isKownTextPanel.Visibility = Visibility.Collapsed;
            //ShowChineseButton.Visibility = Visibility.Collapsed;
            //ForgetWordButton.IsEnabled = true;
            //RemeberWordButton.IsEnabled = true;
        }

        /// <summary>
        /// 显示当前单词
        /// </summary>
        private void ShowWord()
        {
            var et = new ExecuteTimer(false);

            if (_currentWord == null)
            {
                Tools.ShowMessage("目前没有需要记忆的单词");
                HideAllControls();
                return;
            }

            et.Show();

            DataContext = _currentWord;
            et.Show("DataContext");

            ShowAllControls();
            et.Show("ShowAllControls");

            HideChinesePanel();
            ShowIsKnowPanel();

            ShowWordInfo();

            //设置词组、同义词的绑定关系
            SetItemsSource();
            et.Show("SetItemsSource");

            //显示单词的发音文件
            var isVoiceExist = ShowVoiceImage();
            et.Show("ShowVoiceImage");

            ////如果存在发音文件，并且允许自动播放，则直接播放声音
            if (isVoiceExist && new UserConfig().IsAutoPlayVoice)
            {
                PlayVoice();
            }

            et.Show("PlayVoice");
        }

        /// <summary>
        /// 设置词组、同义词的绑定关系
        /// </summary>
        private void SetItemsSource()
        {
            //词组
            var wordGroups = _currentWord.WordGroups;
            if (new UserConfig().IsShowWordGroup && (wordGroups != null) && (wordGroups.Count != 0))
            {
                wordGroupListBox.ItemsSource = wordGroups;
                wordGroupStackPanel.Visibility = Visibility.Visible;
            }
            else
            {
                wordGroupStackPanel.Visibility = Visibility.Collapsed;
            }

            //例句
            var sentences = _currentWord.Sentences;
            if (new UserConfig().IsShowSentence && (sentences != null) && (sentences.Count != 0))
            {
                sentenceListBox.ItemsSource = sentences;
                sentenceStackPanel.Visibility = Visibility.Visible;
            }
            else
            {
                sentenceStackPanel.Visibility = Visibility.Collapsed;
            }

            //同义词
            var synonyms = _currentWord.Synonyms;
            if (new UserConfig().IsShowSynonym && (synonyms != null) && (synonyms.Count != 0))
            {
                synonmyListBox.ItemsSource = synonyms;
                synonmyLStackPanel.Visibility = Visibility.Visible;
            }
            else
            {
                synonmyLStackPanel.Visibility = Visibility.Collapsed;
            }
        }

        /// <summary>
        /// 显示单词的发音文件
        /// </summary>
        private bool ShowVoiceImage()
        {
            var et = new ExecuteTimer(false);
            var tmp = _currentWord.English;
            et.Show("getenglish");
            var isExist = VoiceManager.IsVoiceExist(tmp);

            et.Show("IsVoiceExist");

            ((BitmapImage)voiceButton.ImageSource).UriSource = isExist
                ? new Uri("/Images/voice-yes.png", UriKind.Relative)
                : new Uri("/Images/voice-no.png", UriKind.Relative);
            et.Show("SetValue");

            return isExist;
        }

        /// <summary>
        /// 显示当前单词进度
        /// </summary>
        private void ShowWordInfo()
        {

            bookNameTextBlock.Text = WordBookManager.GetCurrentBook().BookName;
            wordbookTextBlock.Text = _currentWord.WordStatus;
            remeberLevelTextBlock.Text = _currentWord.IsInTheWordBook
                ? string.Format(@"{0} / {1}", _currentWord.RememberLevel + 1, SystemConfig.AchievementRememberLevel + 1)
                : string.Format(@"{0} / {1}", _currentWord.RememberTimes + 1, SystemConfig.NewWordRemeberTimes);

#if DEBUG
            debugMessagePanel.Visibility = Visibility.Visible;
            queueCountTextBlock.Text = string.Format(@"记住{0} 共{1} 队列{2}  ",
                   WordBookManager.WordBook.Count(x => x.IsInTheWordBook),
                   WordBookManager.WordBook.Count, WordQueueManager.Count);
#endif
        }

        /// <summary>
        /// 显示第一个单词
        /// </summary>
        private void ShowFirstWord()
        {
            var et = new ExecuteTimer(false);

            //获取下一个单词
            _currentWord = WordBookManager.GetNextWord();
            et.Show("GetNextWord");

            ShowWord();
            et.Show("ShowWord");
        }

        /// <summary>
        /// 隐藏所有控件
        /// </summary>
        private void HideAllControls()
        {
            ContentPanel.Visibility = Visibility.Collapsed;
            buttonPanel.Visibility = Visibility.Collapsed;
            TitlePanel.Visibility = Visibility.Collapsed;
            nowordPanel.Visibility = Visibility.Visible;
        }

        /// <summary>
        /// 显示所有控件
        /// </summary>
        private void ShowAllControls()
        {
            ContentPanel.Visibility = Visibility.Visible;
            buttonPanel.Visibility = Visibility.Visible;
            TitlePanel.Visibility = Visibility.Visible;
            nowordPanel.Visibility = Visibility.Collapsed;
            contentScrollViewer.ScrollToVerticalOffset(0);

        }

        /// <summary>
        /// 显示 是否认识的面板
        /// </summary>
        private void ShowIsKnowPanel()
        {
            isKownTextPanel.Visibility = Visibility.Visible;
            isKownButtonPanel.Visibility = Visibility.Visible;
        }

        /// <summary>
        /// 隐藏 是否认识的面板
        /// </summary>
        private void HideIsKnowPanel()
        {
            isKownTextPanel.Visibility = Visibility.Collapsed;
            isKownButtonPanel.Visibility = Visibility.Collapsed;
        }

        /// <summary>
        /// 显示 是否正确的面板
        /// </summary>
        private void ShowIsRightPanel()
        {
            chinesePanel.Visibility = Visibility.Visible;
            isRightButtonPanel.Visibility = Visibility.Visible;
        }

        /// <summary>
        /// 隐藏 是否正确的面板
        /// </summary>
        private void HideIsRightPanel()
        {
            isRightButtonPanel.Visibility = Visibility.Collapsed;
        }

        /// <summary>
        /// 显示 下一个按钮的面板
        /// </summary>
        private void ShowNextPanel()
        {
            chinesePanel.Visibility = Visibility.Visible;
            nextButtonPanel.Visibility = Visibility.Visible;
        }

        /// <summary>
        /// 隐藏下一个按钮的面板
        /// </summary>
        private void HideNextPanel()
        {
            nextButtonPanel.Visibility = Visibility.Collapsed;
        }
        #endregion

        #region test

        private void testButton_Click(object sender, EventArgs e)
        {
            //MarketplaceDetailTask _marketPlaceDetailTask = new MarketplaceDetailTask();
            //_marketPlaceDetailTask.Show();
            //TestProgressIndicator();

            //DBTest.CreateSysDB();
            //testListBox.Visibility = Visibility.Visible;
            //using (var db = new UserDataContext())
            //{
            //    testListBox.ItemsSource = db.TableUserWordEntities.ToList();
            //}
            //testListBox.ItemsSource = new SysDataContext().TableDictionaryEntities.ToList();
        }

        private ProgressIndicator _progressIndicator;
        private void TestProgressIndicator()
        {
            if (null == _progressIndicator)
            {
                _progressIndicator = new ProgressIndicator();
                _progressIndicator.IsVisible = true;
                SystemTray.ProgressIndicator = _progressIndicator;
            }

            _progressIndicator.IsIndeterminate = true;
        }

        #endregion




    }
}